const jsonServer = require("json-server");

const Joi = require("joi");
const md5 = require("md5");

const server = jsonServer.create();
const schema = Joi.object({
  username: Joi.string()
    .pattern(/^[\w]{4,16}$/)
    .required()
    .custom((value, helpers) => {
      const v = router.db.get("users").find({ username: value }).value();
      if (v) {
        return helpers.error("any.invalid");
      }
      return value;
    })
    .messages({
      "any.required": "{{#key}} is required",
      "string.pattern.base": "{{#key}} must be between 4 and 16 characters ",
      "string.empty": "{{#key}} is not allowed to be empty",
      "any.invalid": "{{#key}} already exists",
    }),
  password: Joi.string()
    .pattern(/^[\w]{4,16}$/)
    .required()
    .messages({
      "any.required": "{{#key}} is required",
      "string.pattern.base": "{{#key}} must be between 4 and 16 characters",
      "string.empty": "{{#key}} is not allowed to be empty",
    }),
});
// 添加用户
server.post("/users", async (req, res, next) => {
  try {
    const { password } = await schema.validateAsync(req.body, {
      abortEarly: false,
    });
    req.body.password = md5(password);
    next();
  } catch (err) {
    res.status(401).send({
      status: 401,
      success: false,
      message: err.details.map((el) => el.message)[0],
    });
  }
});

// 更新用户
server.put("/users", async (req, res, next) => {
  try {
    await schema.validateAsync(req.body);
    next();
  } catch (err) {
    res.status(401).send({
      status: 401,
      success: false,
      message: err.details.map((el) => el.message)[0],
    });
  }
});

module.exports = () => server;
